package com.softtown.common.utils;

import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.PutObjectRequest;
import com.softtown.common.exception.ErrorCode;
import com.softtown.common.exception.RenException;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: Dingyayong
 * @Date: 2019/11/19 17:55
 * @Description:
 */
public class AliFileUpload {
    static String endpoint = "http://oss-cn-shanghai.aliyuncs.com";
    static String accessKeyId = "LTAI4Fc9debuKnbQAxXTvwFu";
    static String accessKeySecret = "qfMcwiCYxwiTFPzNnKANxVQqN1aVhh";
    static String AlibucketName = "st-service";
    static OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    public static String uploadByAli(InputStream inputStream, String key){
        URL signedUrl =null;
        try {
            PutObjectRequest putObjectRequest = new PutObjectRequest(AlibucketName, key,inputStream);
            ossClient.putObject(putObjectRequest);
            Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
            GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(AlibucketName, key, HttpMethod.GET);
            // 设置过期时间。
            request.setExpiration(expiration);
            // 生成签名URL（HTTP GET请求）。
            signedUrl = ossClient .generatePresignedUrl(request);
            System.out.println("signed url for getObject: " + signedUrl);
            ossClient.shutdown();
        } catch (Exception e) {
            throw new RenException(ErrorCode.OSS_UPLOAD_FILE_ERROR, e, "");
        }
        return String.valueOf(signedUrl);
    }
}
